package com.jse.beetl;

import java.util.Arrays;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.beetl.core.GroupTemplate;
import org.beetl.core.Template;
import org.beetl.ext.web.WebRenderExt;
import org.nutz.dao.Dao;
import org.nutz.ioc.impl.PropertiesProxy;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.util.NutMap;
import org.nutz.mvc.Mvcs;

import com.jse.plug.JseSession;
import com.jse.service.EhcacheService;

@IocBean
public class GlobalExt implements WebRenderExt {

	static long version = System.currentTimeMillis();

	@Override
	public void modify(Template template, GroupTemplate gt, HttpServletRequest req, HttpServletResponse resp) {
		// js,css 的版本编号
		template.binding("version", version);

		PropertiesProxy conf = Mvcs.getIoc().get(PropertiesProxy.class, "conf");
		NutMap obj = new NutMap();
		obj.put("www", conf.get("web.www"));
		obj.put("gen", conf.get("web.domain"));
		obj.put("uuid", UUID.randomUUID().toString());
		obj.put("root",
				req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + req.getContextPath() + "/");
		obj.put("url", req.getScheme() + "%3A%2F%2F" + req.getServerName() + "%3A" + req.getServerPort()
				+ req.getContextPath() + "%2F");
		obj.put("prj", req.getContextPath());
		obj.put("req", req);
		EhcacheService cache = Mvcs.getIoc().get(EhcacheService.class);
		Dao dao = Mvcs.getIoc().get(Dao.class);
		obj.put("cache", cache);
		obj.put("dao", dao);
		JseSession sess = (JseSession) Mvcs.getHttpSession();
		obj.put("sess", sess);
		obj.put("app", Mvcs.getServletContext());
		NutMap p = NutMap.NEW();
		req.getParameterMap().forEach((k, v) -> {
			p.put(k, v.length==1 ? v[0] : Arrays.asList(v));
		});
		List<String> args=Mvcs.getActionContext().getPathArgs();
		obj.put("args", args);
		obj.put("p", p);
		template.binding(obj);
	}
}